using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.bankaccounts;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.bankaccounts
{
    /// <summary>
    /// 新增银行账户命令处理器
    /// </summary>
    public class AddBankAccountCommandHandler : IRequestHandler<AddBankAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BankAccount> _bankAccountRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddBankAccountCommandHandler> _logger;

        public AddBankAccountCommandHandler(
            IBaseRepository<BankAccount> bankAccountRepository,
            IMapper mapper,
            ILogger<AddBankAccountCommandHandler> logger)
        {
            _bankAccountRepository = bankAccountRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增银行账户命令
        /// </summary>
        /// <param name="request">新增银行账户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新增结果</returns>
        public async Task<ApiResult<int>> Handle(AddBankAccountCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始新增银行账户，关联实体ID: {RelatedEntityId}, 实体类型: {RelatedEntityType}, 账户号码: {AccountNumber}", 
                    request.RelatedEntityId, request.RelatedEntityType, request.AccountNumber);

                // 检查账户号码是否已存在
                var existingAccount =  _bankAccountRepository.GetAll().FirstOrDefault(
                    ba => ba.AccountNumber == request.AccountNumber && !ba.IsDeleted);

                if (existingAccount != null)
                {
                    _logger.LogWarning("银行账户号码已存在: {AccountNumber}", request.AccountNumber);
                    
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "该银行账户号码已存在",
                        data = 0
                    };
                }

                // 映射到实体
                var bankAccount = _mapper.Map<BankAccount>(request);
                bankAccount.CreatedTime = DateTime.Now;
                bankAccount.CreatedBy = 1; // 后续可以从当前用户上下文获取

                // 添加到数据库
                await _bankAccountRepository.AddAsync(bankAccount);

                _logger.LogInformation("成功新增银行账户，银行账户ID: {BankAccountId}, 账户号码: {AccountNumber}", 
                    bankAccount.Id, bankAccount.AccountNumber);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.Ok,
                    message = "新增银行账户成功",
                    data = bankAccount.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增银行账户时发生异常，关联实体ID: {RelatedEntityId}", request.RelatedEntityId);
                
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"新增银行账户时发生异常: {ex.Message}",
                    data = 0
                };
            }
        }
    }
}